package cn.xo68.boot.groovyscript.engine;

import cn.xo68.boot.groovyscript.common.ScriptBuilder;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import java.util.Map;

/**
 * groovy脚本执行器
 * @author wuxie
 * @date 2018-12-18
 */
public class GroovyScriptExcutor {

    public static Object excute(ScriptBuilder scriptBuilder, Map<String,Object> vars){
        return excute(scriptBuilder.build(), vars);
    }

    public static Object excute(ScriptBuilder scriptBuilder, Binding binding){
        return excute(scriptBuilder.build(), binding);
    }

    public static Object excute(String havReturnScriptString, Map<String,Object> vars){
        Binding binding = new Binding();
        if(vars!=null){
            for (Map.Entry<String,Object> kv: vars.entrySet()) {
                binding.setVariable(kv.getKey(), kv.getValue());
            }
        }
        return excute(havReturnScriptString,binding);
    }

    public static Object excute(String havReturnScriptString,Binding binding){

        GroovyShell groovyShell = new GroovyShell(binding);
        Object resultValue =groovyShell.evaluate(havReturnScriptString);
        return resultValue;
    }
}
